import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { Link,connect,history } from 'umi'
import { queryContractDayList,terminationContract} from '../service'
import { Tooltip,Tabs,Divider,message,Popconfirm,notification,Button,DatePicker} from 'antd'
import {contractTypeList} from "@/utils/constant"
import CreateForm from '@/pages/Personnel/Entry/Contract/List/components/CreateForm'
import AddContractForm from './components/AddContractForm'
import moment from 'moment'
import {saveContractInfo} from "@/pages/Personnel/Entry/Contract/service";
const  { TabPane } = Tabs;

const TableList = () => {
  const actionRef = useRef()
  const [tabIndex, setTabIndex] = useState("1")
  const [visible, setVisible] = useState(null)
  const [record,setRecord] = useState(null)
  const [loading,setLoading] = useState(false)
  const [addVisible,setAddVisible] = useState(false)

  const handleChangTabIndex = (key) => {
    setTabIndex(key)
    if(key === 2){
      actionRef.current.reload()
    }
  };

  const handleCancel = () => {
    setVisible(false)
    setAddVisible(false)
    setRecord(null)
  };

  const handleSubmit = (values) => {
    setLoading(true)
    saveContractInfo(values).then((res) => {
      if(res.flag){
        message.success('合同发送成功！');
        handleCancel()
        actionRef.current.reload()
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false)
    })
  };

  const renew = (record) =>{
    setVisible(true)
    setRecord(record)
  };

  const addContract = () =>{
    setAddVisible(true)
  };

  const termination = (id) =>{
    terminationContract(id).then(res => {
      if(res.flag){
        message.success('合同终止成功！');
        actionRef.current.reload()
      }else{
        message.error(res.error)
      }
    })
  };

  const itemDetail = (item) => {
    history.push(`/info/details/${item.oid}`)
  };

  const columns = [
    {
      title: '流程id',
      dataIndex: 'flowId',
      hideInSearch: true,
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '签订人',
      dataIndex: 'name',
    },
    {
      title: '合同名称',
      dataIndex: 'contractName',
      hideInSearch: true
    },
    {
      title: '合同开始时间',
      dataIndex: 'contractStartTime',
      hideInSearch: true
    },
    {
      title: '合同结束时间',
      dataIndex: 'contractEndTime',
      hideInSearch: true
    },
    {
      title: '合同类型',
      dataIndex: 'type',
      valueEnum: {
        0: { text: contractTypeList[0].label },
        1: { text: contractTypeList[1].label },
      },
    },
    {
      title: '合同状态',
      dataIndex: 'status',
      valueEnum: {
        1: { text: '未生效', status: 'Default' },
        2: { text: '已生效', status: 'Success' },
        3: { text: '合同过期', status: 'Default' },
        4: { text: '合同终止', status: 'Default' },
      },
    },
    {
      title: '合同地址',
      dataIndex: 'contractOssUrl',
      hideInSearch: true,
      onCell: ()=>{
        return {
          style:{
            maxWidth:100,
            overflow:'hidden',
            whiteSpace:'nowrap',
            textOverflow:'ellipsis',
            cursor:'pointer',
          }
        }
      },
      render: (text) =>{
        return <Tooltip placement="topLeft" title={text}><a href={text} target="_blank">{text}</a></Tooltip>
      }
    },
    {
      title: '签订开始日期',
      dataIndex: 'beginDate',
      hideInTable: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
      renderFormItem: (item, props) => {
        return <DatePicker className='widthStyle' {...props} picker="date"/>;
      }
    },
    {
      title: '签订结束日期',
      dataIndex: 'endDate',
      hideInTable: true,
      render: (text) => {
        return text ? moment(text).format('YYYY-MM-DD') : ''
      },
      renderFormItem: (item, props) => {
        return <DatePicker className='widthStyle' {...props} picker="date"/>;
      },
    },
    {
      title: '签订时间',
      dataIndex: 'signedTime',
      hideInSearch: true,
      render: (text) => {
        return text !== "-"?moment(text).format('YYYY-MM-DD'):''
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '10%',
      render: (item, record) => (
        <>
          <a onClick={() => renew(record)}>续签</a>
          {
            (record.status === 2) && <>
              <Divider type="vertical"/>
              <Popconfirm title={`是否确认终止合同?`}
                          onConfirm={() => termination(record.id)}
                          okText="是" cancelText="否">
                <a>终止</a>
              </Popconfirm>
            </>
          }
          <Divider type="vertical"/>
          <a onClick={() => itemDetail(record)}>详情</a>
        </>
      ),
    },
  ]

  const alreadyColumns = [
    {
      title: '流程id',
      dataIndex: 'flowId',
      hideInSearch: true,
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '签订人',
      dataIndex: 'name',
    },
    {
      title: '合同名称',
      dataIndex: 'contractName',
      hideInSearch: true
    },
    {
      title: '合同开始时间',
      dataIndex: 'contractStartTime',
      hideInSearch: true
    },
    {
      title: '合同结束时间',
      dataIndex: 'contractEndTime',
      hideInSearch: true
    },
    {
      title: '合同类型',
      dataIndex: 'type',
      valueEnum: {
        0: { text: contractTypeList[0].label },
        1: { text: contractTypeList[1].label },
      },
    },
    {
      title: '合同状态',
      dataIndex: 'status',
      valueEnum: {
        1: { text: '未生效', status: 'Default' },
        2: { text: '已生效', status: 'Success' },
        3: { text: '合同过期', status: 'Default' },
        4: { text: '合同终止', status: 'Default' },
      },
    },
    {
      title: '合同地址',
      dataIndex: 'contractOssUrl',
      hideInSearch: true,
      onCell: ()=>{
        return {
          style:{
            maxWidth:100,
            overflow:'hidden',
            whiteSpace:'nowrap',
            textOverflow:'ellipsis',
            cursor:'pointer',
          }
        }
      },
      render: (text) =>{
        return <Tooltip placement="topLeft" title={text}><a href={text} target="_blank">{text}</a></Tooltip>
      }
    },
    {
      title: '签订开始日期',
      dataIndex: 'beginDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: '签订结束日期',
      dataIndex: 'endDate',
      valueType: 'date',
      hideInTable: true,
    },
    {
      title: '签订时间',
      dataIndex: 'signedTime',
      hideInSearch: true,
      render: (text) => {
        return text !== "-"?moment(text).format('YYYY-MM-DD'):''
      },
    }
  ]

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="1" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="1">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryContractDayList(params,tabIndex)}
            columns={columns}
            toolBarRender={(action, { selectedRows }) => [
              <Button type="primary" onClick={() => addContract()}>新建</Button>,
            ]}
          />
          <CreateForm
            record={record}
            loading={loading}
            visible={visible}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
          <AddContractForm
            record={record}
            loading={loading}
            visible={addVisible}
            onCancel={handleCancel}
            onSubmit={handleSubmit}
          />
        </TabPane>
        <TabPane tab="已办理" key="2">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryContractDayList(params,tabIndex)}
            columns={alreadyColumns}
          />
        </TabPane>
      </Tabs>
    </PageHeaderWrapper>
  )
}

export default connect(() => ({
}))(TableList)
